//
//  UCenterViewController.m
//  OrderSeat
//
//  Created by 王威 on 14-1-14.
//  Copyright (c) 2014年 wangwei. All rights reserved.
//

#import "UCenterViewController.h"
#import "UIImageView+WebCache.h"
#import "LoggedViewController.h"
#import "UpdatePassViewController.h"
#import "UpdatePhoneViewController.h"
#import "ForgotPasswordViewController.h"

#define BTN_TEL_TAG 1003
#define BTN_PASS_TAG 1004

#define TempPhoto @"TempPhoto.jpg"

@interface UCenterViewController ()<UIActionSheetDelegate>

@property (assign, nonatomic) BOOL isUpload;
@property (strong, nonatomic) NSString *filename;
@property (strong, nonatomic) UIActionSheet *actionSheet;
@property (strong, nonatomic) UIImagePickerController *imagePicker;

@end

@implementation UCenterViewController

- (id)init
{
    self = [super initWithNibClass:[UCenterViewController class]];
    if (self) {
        _filename = [[NSDate date] toStringWithFormat:@"yyyyMMddHHmmss"];
        _filename = [NSString stringWithFormat:@"%@.jpg",_filename];
        _dataSource = [[UCenterDataSource alloc] initWithVC:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
    
    [_dataSource fetchUserInfo];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
    [_telBtn setTitleForNormal:[AppSetting tel]];
}

- (void)setupUI
{
    [self createLeftButton];
    [self setNavigationTitle:@"个人会员中心"];
    [self.view addTarget:self action:@selector(viewTaped:)];
    
    _actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"拍照", nil];
    _imagePicker = [[UIImagePickerController alloc] init];
    _imagePicker.delegate = self;
    
    [self reLayoutSubviews];
}

- (void)leftButtonClick:(id)sender
{
    [self pushOrPopViewController:[LoggedViewController class]];
    [[AppDelegate sharedInstance] showTabBar:self.tabBarController];
}

- (IBAction)saveAction:(id)sender
{
    [self updateUserAction];
}

- (void)reLayoutSubviews
{
    [_headView autoHeight];
    [_bodyView autoHeightNoMargin];
    [UIView autoLayoutVertical:@[_headView, _bodyView]];
    [UIView drawBorders:@[_headView, _bodyView]];
    
    _theScrollview.height = ScreenHeight - NavBarHeight;
    [_theScrollview autoHeightNoMargin];
}

- (void)viewTaped:(id)sender
{
    [_nicknameTF resignFirstResponder];
    [_nameTF resignFirstResponder];
    [_emailTF resignFirstResponder];
    
    [_theScrollview setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.theScrollview setContentOffset:CGPointMake(0, textField.tag > 3 ? 200 : 120) animated:YES];
}

- (void)setFormValues:(NSDictionary *)data
{
    NSString *huiyuan = [data objectForKey:@"huiyuan"];
    NSString *touxiang = [data objectForKey:@"touxiang"];
    NSString *nicheng = [data objectForKey:@"nicheng"];
    NSString *xingshi = [data objectForKey:@"xingshi"];
    NSString *xb = [data objectForKey:@"xb"];
    NSString *tel = [data objectForKey:@"tel"];
    NSString *email = [data objectForKey:@"email"];
    
    if (![[NSNull null] isEqual:huiyuan] && ![huiyuan isEqualToString:S_EMPTY]) {
        [AppSetting setUserName:huiyuan];
    }
    
    if (![[NSNull null] isEqual:touxiang] && ![touxiang isEqualToString:S_EMPTY]) {
        [_photoView setImageWithURL:[NSURL URLWithString:touxiang]];
    }else {
        _photoView.image = [UIImage imageNamed:@"user_avatar.png"];
    }
    
    if (![[NSNull null] isEqual:nicheng])_nicknameTF.text = nicheng;
    if (![[NSNull null] isEqual:xingshi]) _nameTF.text = xingshi;
    if (![[NSNull null] isEqual:tel]) [_telBtn setTitleForNormal:tel];
    if (![[NSNull null] isEqual:email]) _emailTF.text = email;
    if (![[NSNull null] isEqual:xb]) {
        _sirBtn.selected = [xb isEqualToString:@"先生"];
        _ladyBtn.selected = !_sirBtn.selected;
    }
    
    [AppSetting setTel:tel];
}

- (IBAction)buttonAction:(id)sender
{
    _sirBtn.selected = _ladyBtn.selected = NO;
    [sender setSelected:YES];
}

- (IBAction)changeAction:(id)sender
{
    if ([sender tag] == BTN_TEL_TAG) {
        UpdatePhoneViewController *updatePhoneVC = [[UpdatePhoneViewController alloc] init];
        [self pushViewController:updatePhoneVC];
    }
    
    if ([sender tag] == BTN_PASS_TAG) {
        UpdatePassViewController *updatePassVC = [[UpdatePassViewController alloc] init];
        [self pushViewController:updatePassVC];
    }
}

- (void)updateUserAction
{
    NSString *nicheng = _nicknameTF.text;
    NSString *xingshi = _nameTF.text;
    NSString *xb = _sirBtn.selected ? @"先生" : @"女士";
    NSString *tel = _telBtn.titleLabel.text;
    NSString *email = _emailTF.text;

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:nicheng forKey:@"nicheng"];
    [params setObject:xingshi forKey:@"xingshi"];
    [params setObject:xb forKey:@"xb"];
    [params setObject:tel forKey:@"tel"];
    [params setObject:email forKey:@"email"];
    
    [_dataSource updateUser:params];
}

- (IBAction)takePhotoAction:(id)sender
{    
    if (![self.actionSheet isVisible]) {
        [self.actionSheet showInView:[UIApplication sharedApplication].keyWindow];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex){
        case 0: {
            [self showImagePicker:NO];
            break;
        }
        case 1: {
            [self showImagePicker:YES];
            break;
        }
    }
}

- (void)showImagePicker:(BOOL)isCamera
{
    if (isCamera) {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        self.imagePicker.allowsEditing = YES;
    }else{
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    // do nothing here
}

// 完成选取
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)_picker
{
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)_picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    if (_picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        _picker.title = @"拍照";
    }
    
    [self dismissViewControllerAnimated:YES completion:^{
        UIImage *copyImage = [image compressForSize:CGSizeMake(100, 100)];
        [self saveImage:copyImage WithName:TempPhoto];
        
        [_dataSource updatePhoto];
        
        [[UIApplication  sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
        _photoView.image = image;
    }];
}

- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSString* fullPathToFile = [AppSetting filePath:imageName];
    
    NSData* imageData = UIImageJPEGRepresentation(tempImage, 0.5);
    [imageData writeToFile:fullPathToFile atomically:NO];
}

@end

#define USER_INFO_TAG 1001
#define UPDATE_USER_TAG 1002
#define UPDATE_PHOTO_TAG 1007

@implementation UCenterDataSource

- (id)initWithVC:(id)Controller
{
    self = [super init];
    if (self) {
        self.Controller = Controller;
    }
    return self;
}

- (void)fetchUserInfo
{
    [SVProgressHUD showWithStatus:@"正在获取用户信息..."];
    
    NSString *url = [NSString stringWithFormat:API_USER_INFO, [AppSetting userName]];
    [self get:url tag:USER_INFO_TAG];
}

- (void)updatePhoto
{
    [SVProgressHUD showWithStatus:@"正在上传用户图像..."];
    
    NSString *url = [NSString stringWithFormat:API_UPDATE_PHOTO, [AppSetting userName]];
    [self post:url file:[AppSetting filePath:TempPhoto] extraParams:nil tag:UPDATE_PHOTO_TAG];
}

- (void)updateUser:(NSDictionary *)params
{
    [SVProgressHUD showWithStatus:@"正在提交修改信息..."];

    NSString *url = [NSString stringWithFormat:API_UPDATE_USER,[AppSetting userName]];
    [self post:url params:params tag:UPDATE_USER_TAG];
}

- (void)requestFinished:(ASIHTTPRequest*)request
{
    NSLog(@"%@", request.responseString);
    NSDictionary *json = [request.responseData JSONValue];
    NSDictionary *data = [json objectForKey:@"data"];
    
    [self processRequest:data withTag:request.tag];
}

- (void)processRequest:(NSDictionary *)data withTag:(int)tag
{
    if (tag == USER_INFO_TAG) {
        [SVProgressHUD dismiss];
        [_Controller setFormValues:data];
        return;
    }
    
    if (tag == UPDATE_USER_TAG) {
        if ([[data objectForKey:@"state"] intValue] == 1) {
            [SVProgressHUD dismissWithSuccess:@"用户信息修改成功！"];
        }
        if ([[data objectForKey:@"state"] intValue] == 2) {
            [SVProgressHUD dismissWithError:@"用户信息修改失败！"];
        }
        return;
    }
    
    if (tag == UPDATE_PHOTO_TAG) {
        [SVProgressHUD dismissWithSuccess:@"用户图像上传成功！"];
        [AppSetting setIsUpdatePhoto:YES];
    }
}

@end



